#!/usr/bin/python3
# ******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# ******************************************************************************/
import argparse
import os
from collections import OrderedDict

import yaml

rpm_spec_dict = dict()
rpm_info_dict = dict()
current_path = os.path.abspath(os.path.dirname(__file__))
pkg_list_file = os.path.join(current_path, 'pkglist.txt')


def find_spec(source_path):
    """
    查找所有的spec文件
    :param source_path: 源码包所在路径
    :return: rpm_spec_dict{‘包名’：‘spec路径’}
    """
    with open(pkg_list_file, 'r') as file:
        pkg_list = file.read()
    for dir in os.listdir(source_path):
        if dir in pkg_list:
            file_path = os.path.join(source_path, dir)
            for file in os.listdir(file_path):
                if file.endswith(".spec"):
                    rpm_spec_dict[dir] = os.path.join(file_path, file)
                    break

    return rpm_spec_dict


def read_rpm_info():
    """
    读取spec文件中rpm信息
    :return: rpm信息
    """
    for rpm_name, spec_file in rpm_spec_dict.items():
        if os.path.isfile(spec_file):
            with open(spec_file, 'r') as file:
                summary = ""
                description = ""
                url = ""
                description_start = False
                for line in file.readlines():
                    line = line.strip()
                    if "summary:" in line.lower():
                        summary = line.split('Summary:')[-1].strip()
                    if "url:" in line.lower():
                        url = line.split('URL:')[-1].strip()
                    if "%description" in line:
                        description_start = True
                        description += line.strip('%description').split(':')[-1].strip()
                        continue
                    if description_start and line.startswith('%'):
                        break
                    if description_start:
                        description += line
                rpm_info_dict[rpm_name] = {"summary": summary, "url": url, "description": description}

    return rpm_info_dict


def create_repo():
    """
    创建建仓yaml文件
    :return: None
    """
    result_file = os.path.join(current_path, 'result.yaml')
    result_dict = dict()
    result_info_list = list()
    with open(result_file, 'w', encoding="utf-8") as file:
        for rpm_name, rpm_info in rpm_info_dict.items():
            result_info_dict = OrderedDict()
            result_info_dict['name'] = rpm_name
            result_info_dict['description'] = rpm_info.get('summary')
            result_info_dict['upstream'] = rpm_info.get('url')
            result_info_dict['branches'] = [{'name': 'master', 'type': 'protected'}]
            result_info_dict['type'] = 'public'
            result_info_list.append(result_info_dict)

        result_dict['repositories'] = result_info_list
        ordered_yaml_dump(result_dict, file)


def ordered_yaml_dump(data, stream=None, Dumper=yaml.SafeDumper, **kwds):
    """
    顺序写入字典内容
    :param data:
    :param stream:
    :param Dumper:
    :param kwds:
    :return:
    """

    class OrderedDumper(Dumper):
        pass

    def _dict_representer(dumper, data):
        return dumper.represent_mapping(
            yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
            data.items())

    OrderedDumper.add_representer(OrderedDict, _dict_representer)
    return yaml.dump(data, stream, OrderedDumper, **kwds)


if __name__ == '__main__':
    args_parse = argparse.ArgumentParser()
    args_parse.add_argument('-p', '--path', type=str, action='store', help='path of source packages')
    args = args_parse.parse_args()
    find_spec(args.path)
    read_rpm_info()
    create_repo()
